<!DOCTYPE html>
<html class="ui-page-login">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
		<style>
			.area {
				margin: 20px auto 0px auto;
			}
			
			.mui-input-group {
				margin-top: 10px;
			}
			
			.mui-input-group:first-child {
				margin-top: 20px;
			}
			
			.mui-input-group label {
				width: 22%;
			}
			
			.mui-input-row label~input,
			.mui-input-row label~select,
			.mui-input-row label~textarea {
				width: 78%;
			}
			
			.mui-checkbox input[type=checkbox],
			.mui-radio input[type=radio] {
				top: 6px;
			}
			
			.mui-content-padded {
				margin-top: 25px;
			}
			
			.mui-btn {
				padding: 10px;
			}
			
			.link-area {
				display: block;
				margin-top: 25px;
				text-align: center;
			}
			
			.spliter {
				color: #bbb;
				padding: 0px 8px;
			}
			
			.oauth-area {
				position: absolute;
				bottom: 20px;
				left: 0px;
				text-align: center;
				width: 100%;
				padding: 0px;
				margin: 0px;
			}
			
			.oauth-area .oauth-btn {
				display: inline-block;
				width: 50px;
				height: 50px;
				background-size: 30px 30px;
				background-position: center center;
				background-repeat: no-repeat;
				margin: 0px 20px;
				/*-webkit-filter: grayscale(100%); */
				border: solid 1px #ddd;
				border-radius: 25px;
			}
			
			.oauth-area .oauth-btn:active {
				border: solid 1px #aaa;
			}
			
			.oauth-area .oauth-btn.disabled {
				background-color: #ddd;
			}
		</style>

	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title">登录</h1>
		</header>
		<div class="mui-content">
			<form id='login-form' class="mui-input-group">
				<div class="mui-input-row">
					<label>账号</label>
					<input id='account' type="text" class="mui-input-clear mui-input" placeholder="请输入账号">
				</div>
				<div class="mui-input-row">
					<label>密码</label>
					<input id='password' type="password" class="mui-input-clear mui-input" placeholder="请输入密码">
				</div>
			</form>
			<form class="mui-input-group">
				<ul class="mui-table-view mui-table-view-chevron">
					<li class="mui-table-view-cell">
						自动登录
						<div id="autoLogin" class="mui-switch">
							<div class="mui-switch-handle"></div>
						</div>
					</li>
				</ul>
			</form>
			<div class="mui-content-padded">
				<button id='login' class="mui-btn mui-btn-block mui-btn-primary">登录</button>
				<div class="link-area"><a id='reg'>注册账号</a>
				</div>
			</div>
		</div>
		<script src="js/mui.min.js"></script>
		<script src="js/mui.enterfocus.js"></script>
		<script src="js/axios.min.js"></script>
		<script src="js/app.js"></script>
		<script src="js/config.js"></script>
		<script>
			(function($, doc) {
				$.init({
					statusBarBackground: '#f7f7f7',
					preloadPages:[{
					    id:'main.html',
					    url:'main.html'           
					}]
				});
	
				$.plusReady(function() {
					plus.screen.lockOrientation("portrait-primary");
					var settings = app.getSettings();
					var state = app.getState();	

					// close splash
					setTimeout(function() {
						//关闭 splash
						plus.navigator.closeSplashscreen();
					}, 600);

					var toMain = function() {
						$.openWindow({
							url: 'main.html',
							id: 'main.html',
							preload: true,
							show: {
								aniShow: 'pop-in'
							},
							styles: {
								popGesture: 'hide'
							},
							waiting: {
								autoShow: false
							}
						});
					};
					
					var errorResponse = function(error){
						console.log(error);
						switch(error.errorcode){
							case 5001:
								console.log(error.errorcode)
								plus.nativeUI.toast("账号或密码错误");
							case 5004:
								console.log(error.errorcode)
								plus.nativeUI.toast("Token过期，重新登录");
						}
					}
					
					var loginAjax = function(loginInfo){
						var loginUrl = config.getLoginUrl();
													
						mui.ajax(loginUrl, {
							data: loginInfo,
							dataType: 'json',//服务器返回json格式数据
							type: 'post',//HTTP请求类型
							success: function(data){
								//服务器返回响应，根据响应结果，分析是否登录成功；
								//保存用户名、密码、token
								var state = {};
								state.mobile = loginInfo.mobile;
								state.password = loginInfo.password;
								state.token = data.token;
								app.createState(state);
								
								
								var info = plus.push.getClientInfo();
								var cid = {};
							    cid.mobile = state.mobile;
							    cid.cid = info.clientid;
							    cid.token = state.token;
							    
							    //推送后端cid，更新数据库
							    var cidUrl = config.getUiUrl();
							    mui.ajax(cidUrl,{
									data: cid,
									dataType: 'json',//服务器返回json格式数据
									type: 'post',//HTTP请求类型
									success: function(data){
										//服务器返回响应，根据响应结果，分析是否登录成功；
										//保存用户名、密码、token
										console.log("推送cid成功")
									},
									error: function(xhr,type,errorThrown){
										//console.log(xhr.response)
										var response = xhr.response;
										//errorResponse(JSON.parse(response));
										console.log(response)
									}
								});						
								
								//进入主页
								toMain();
								
							},
							error: function(xhr,type,errorThrown){
								//console.log(xhr.response)
								var response = xhr.response;
								errorResponse(JSON.parse(response));
							}
						});
					}
					
					//检查 "登录状态/锁屏状态" 开始
					if (settings.autoLogin) {
						var loginInfo = {
							mobile: state.mobile,
							password: state.password
						};
						loginAjax(loginInfo);
					} else {
						app.setState(null);
					}
					
					//检查 "登录状态/锁屏状态" 结束
					var loginButton = doc.getElementById('login');
					var accountBox = doc.getElementById('account');
					var passwordBox = doc.getElementById('password');
					var autoLoginButton = doc.getElementById("autoLogin");
					var regButton = doc.getElementById('reg');
					loginButton.addEventListener('tap', function(event) {
						var loginInfo = {
							mobile: accountBox.value,
							password: passwordBox.value
						};
						
						if(app.loginCheck(loginInfo, function(err) {
								if (err) {
									console.log("登录错误")
									plus.nativeUI.toast(err);
									return;
								}
							})
						){
							console.log("登录");
							loginAjax(loginInfo);
						}							
					});
					$.enterfocus('#login-form input', function() {
						$.trigger(loginButton, 'tap');
					});
					autoLoginButton.classList[settings.autoLogin ? 'add' : 'remove']('mui-active')
					autoLoginButton.addEventListener('toggle', function(event) {
						setTimeout(function() {
							var isActive = event.detail.isActive;
							settings.autoLogin = isActive;
							app.setSettings(settings);
						}, 50);
					}, false);
					
					regButton.addEventListener('tap', function(event) {
						$.openWindow({
							url: 'reg.html',
							id: 'reg',
							preload: true,
							show: {
								aniShow: 'pop-in'
							},
							styles: {
								popGesture: 'hide'
							},
							waiting: {
								autoShow: false
							}
						});
					}, false);

					var backButtonPress = 0;
					$.back = function(event) {
						backButtonPress++;
						if (backButtonPress > 1) {
							plus.runtime.quit();
						} else {
							plus.nativeUI.toast('再按一次退出应用');
						}
						setTimeout(function() {
							backButtonPress = 0;
						}, 1000);
						return false;
					};
				});
				
				document.addEventListener( "plusready", function(){
				    // 监听点击消息事件
				    plus.push.addEventListener( "click", function( msg ) {
				        // 判断是从本地创建还是离线推送的消息
				        switch( msg.payload ) {
				            case "LocalMSG":
				                console.log( "点击本地创建消息启动：" );
				            break;
				            default:
				                console.log( "点击离线推送消息启动：");
				            break;
				        }
				        // 提示点击的内容
				        plus.ui.alert( "click-plus"+msg.content );
				        mui.toast("click-mui"+msg.content)
				    }, false );
				    // 监听在线消息事件
				    plus.push.addEventListener( "receive", function( msg ) {
				        if ( msg.aps ) {  // Apple APNS message
				            console.log( "接收到在线APNS消息：" );
				        } else {
				            console.log( "接收到在线透传消息：" );
				            //plus.nativeUI.toast(msg.payload);
				        }
						var msgJson = JSON.parse(msg.payload);
						
						var content = "请于"+msgJson.startTimestamp+"从"+msgJson.startAddress+"出发，去往"+msgJson.endAddress+"，任务："+msgJson.purpose+"。"
						plus.nativeUI.confirm(content, function(){
							var taskUrl = config.getTaskUrl();
							var state = app.getState();	
	
							var taskJson = {
								"id":msgJson.id,
								"state":0,
								"token":state.token
							};
							
							mui.ajax(taskUrl,{
								data: taskJson,
								dataType: 'json',//服务器返回json格式数据
								type: 'post',//HTTP请求类型
								success: function(data){
									//服务器返回响应，根据响应结果，分析是否登录成功；
									//保存用户名、密码、token
									plus.nativeUI.toast("接单成功");
									var mainPage = plus.webview.getWebviewById('main.html');;
									mui.fire(mainPage,'message', msgJson);
								},
								error: function(xhr,type,errorThrown){
									//console.log(xhr.response)
									var response = xhr.response;
									//errorResponse(JSON.parse(response));
									console.log(response)
								}
							});
						}, {
							"title":msgJson.purpose,
							"buttons":["接单"]
						});
				    }, false );
				}, false );
			}(mui, document));
		</script>
	</body>

</html>